package cn.appsys.controller.deve;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.constant.Constants;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.deve.appinfo.DeveAppInfoService;
import cn.appsys.service.deve.appversion.DeveAppVersionService;


@Controller
@RequestMapping("/deve/appvarsion")
public class DevoAppVersionController {

	
	@Resource
	private DeveAppInfoService deveAppInfoService;
	
	@Resource
	private DeveAppVersionService deveAppVersionService;
	
	//用于保存修改后app版本信息
	@RequestMapping("/appversionmodifysave")
	public String appversionmodifysave(AppVersion appVersion,HttpSession session,
			@RequestParam("attach")MultipartFile attach,Model model,HttpServletRequest request) {
		String apkFileName="";	//用于保存生成好的apk文件名称
		String apkLocPath="";	//用于保存apk文件在tomcat服务器上的绝对路径
		String downloadLink="";	//用于保存下载链接(即apk文件的相对路径)
		if(!attach.isEmpty()){
			//1.得到uploadfiles文件夹的绝对路径到时候将apk文件上传到此目录中
			String path=session.getServletContext().getRealPath("statics/uploadfiles");
			//2.得到源文件名
			String oldFileName=attach.getOriginalFilename();
			//3.获取此源文件名中的文件后缀
			String extension=FilenameUtils.getExtension(oldFileName);
			//4.对此文件的格式进行判断,判断此文件是否是apk格式。
			if(extension.equalsIgnoreCase("apk")){
				//5.获取当前重命名后的apk文件名,格式为: apkName +appVerseionNo
				AppInfo appInfo=deveAppInfoService.queryById(appVersion.getAppId());//通过appId查询app详细
				apkFileName=appInfo.getAPKName()+"-"+appVersion.getVersionNo()+".apk";
				
				//
				File file=new File(path,apkFileName);
				if(!file.exists()){
					file.mkdirs();
				}
				
				
					try {
						attach.transferTo(file);
					} catch (IOException e) {
						e.printStackTrace();
						session.setAttribute("fileUploadError","apk文件上传失败");
					}
				 apkLocPath=path+"\\"+apkFileName;
				 downloadLink=request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
				
			}else{
				model.addAttribute("fileUploadError","您上传 的文件格式不正确");
			}
		}
		//
		DevUser user=(DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
		appVersion.setModifyBy(user.getId());
		appVersion.setModifyDate(new Date());
		appVersion.setDownloadLink(downloadLink);
		appVersion.setApkFileName(apkFileName);
		appVersion.setApkLocPath(apkLocPath);
		int result=deveAppVersionService.updateAppVersion(appVersion);
		if(result>0){
			return "redirect:/deve/appinfo/list";
		}else{
			return "redirect:/deve/appversion/appversionmodifyqvid=" + 
		appVersion.getId()+"&aid"+appVersion.getAppId();
		}
	}
	/**
	 * 删除apk文件功能
	 * @param id app版本id
	 * @return
	 */
	@RequestMapping("/delfile")
	@ResponseBody   //通过@ResponseBody注解将当前方法的返回值输出到浏览器客户端
	public Object delfile(@RequestParam("id")Integer id){
		Map<String, String> map=new HashMap<String, String>();
		if(id == null){
			map.put("result", "failed");
		}else{
			//1、通过app版本id查询当前app版本的详细对象信息，并得到apkLocPath的值
			System.out.println("=============>"+id);
			AppVersion appVersion=deveAppVersionService.getVersionById(id);
			String appLocPath=appVersion.getApkLocPath();
			//2.通过apkLocPath创建一个File文件对象， 并调用File文件对象的delete ()删除方法，实现将apk文件从服务器.上删除的功能。
			System.out.println("===========>"+appLocPath);
			File file=new File(appLocPath);
			if(file.exists()){
				//调用File对象的delete()，实现将apk文件从tomcat服务器上面进行删除
				if(file.delete()){
					//3、调用service,实现将app_version表中apkLocPath、downloadLink、apkFileName这三个字段给清空
					int result=deveAppVersionService.deleteApkFile(id);
					if(result>0){
						//删除成功
						map.put("result", "success");		//apk成功
					}else{
						map.put("result", "failed");
					}
				}
			}else{
				map.put("result", "noexist");
			}
		}
		
		return map;
	}
	
	/**
	 * 负责当用户在页面上点击[修改版本]超链接时，跳到app版本修改页面中
	 * @param vId
	 * @param aid
	 * @param model
	 * @return
	 */
	@RequestMapping("/appversionmodify")
	public String appversionmodify(@RequestParam("vid")Integer vid,
			@RequestParam("aid")Integer aid,Model model){
		//1,通过app的主键id,将当前app的历史版本列表查询出来
		List<AppVersion> appVersionList=deveAppVersionService.getAppVersionByAppId(aid);
		//2.通过版本id,查询当前版本的详细信息
		AppVersion appVersion=deveAppVersionService.getVersionById(vid);
		//3.将历史版本列表,当前版本对象保存到Model对象
		model.addAttribute("appVersionList",appVersionList);
		model.addAttribute("appVersion",appVersion);
		//4.跳转到app版本修改页面中
		return "developer/appversionmodify";
	}
	
	
	@RequestMapping(value="/addversionsave",method=RequestMethod.POST)
	public String addversionsave(AppVersion appVersion,@RequestParam("a_downloadLink")MultipartFile attach,Model model,
			HttpServletRequest request){
		String downLoadLink="";
		String apkLocPath="";
		String apkFileName="";		//用来保存abk文件的名字
		if(!attach.isEmpty()){
			String path=request.getSession().getServletContext().
					getRealPath("statics\\uploadfiles");
			
			String oldFilName=attach.getOriginalFilename();
			String extension=FilenameUtils.getExtension(oldFilName);
			if(extension.equalsIgnoreCase("apk")){
				//如果当前上传的文件其后缀为apk,即认为是合法文件
				AppInfo appInfo=deveAppInfoService.queryById(appVersion.getAppId());
				//为了保证每个用户上传的apk文件的唯一性，我们需要重命名当前apk文件的名字，apk名字的格式: apkName +
				apkFileName=appInfo.getAPKName()+"-"+appVersion.getVersionNo()+".apk";
				//创建File对象
				File file=new File(path,apkFileName);
				if(!file.exists()){
					//判断在tomcat的发布目录下的statics/uploadfiles/目录下是否存在apkFi leName
					//如果不存在，就创建此目录
					file.mkdirs();
				}
				try {
					attach.transferTo(file);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				//下载链接(apk文件的相对路径)
				downLoadLink=request.getContextPath()+"\\statics\\uploadfiles\\"+apkFileName;
				//apk文件在tomcat服务器上的绝对路径
				apkLocPath=path+"\\"+apkFileName;
				System.out.println("apkLocPath"+apkLocPath);
			}else{
				model.addAttribute("fileUploadError","您上传的文件格式不准确,正确的格式为apk");
			}
		}
		//2.得到当前登录对象
		DevUser user=(DevUser)request.getSession().getAttribute(Constants.DEV_USER_SESSION);
		appVersion.setCreatedBy(user.getId());
		appVersion.setCreationDate(new Date());
		appVersion.setDownloadLink(downLoadLink);
		appVersion.setApkFileName(apkFileName);
		appVersion.setApkLocPath(apkLocPath);
		//调用service的新增版本方法实现最终的新增
		try {
			int result=deveAppVersionService.insertAppVersion(appVersion);
			if(result>0){
				//获取到了在新增当前app版本后的主键id,之后还要将app_ info表中version_ id的值 进行修改
				AppInfo appInfo=new AppInfo();
				appInfo.setId(appVersion.getAppId());
				appInfo.setVersionId(appVersion.getId());
				int row=deveAppInfoService.updateAppInfo(appInfo);
				if(row>0){
					return "redirect:/deve/appinfo/list";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/deve/appversion/appversionadd/"+appVersion.getAppId();
	}
	
	/**
	 * 负贵跳转到新增app版本页面appversionadd.jsp,在跳转过去之前，还要将当前app的历史版本列表信息查询出来
	 * @param appId
	 * @return
	 */
	@RequestMapping(value="/appvarsionadd/{id}")
	public String appvarsionadd(@PathVariable("id")Integer appId,Model model){
	//
		List<AppVersion> appVarsionList=deveAppVersionService.getAppVersionByAppId(appId);
		AppVersion appVarsion=new AppVersion();
		appVarsion.setAppId(appId);
		//这里的key写错了. 你要跟appversionadd.jsp页面上的key统一.
		model.addAttribute("appVarsionList",appVarsionList);  
		model.addAttribute("appVersion",appVarsion);  //你这是的key写错到,导致appversionadd.jsp页面中获取不到appId的值
		return "developer/appversionadd";
	}
}
